package com.redwood.report.observer;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;

import com.redwood.report.event.SmsChangeEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Supeng on 2018/8/21.
 * 读取短信
 */

public class ReadSmsObserver extends ContentObserver {
    private static final String SMS_INBOX_URI = "content://sms/inbox";//API level>=23,可直接使用Telephony.Sms.Inbox.CONTENT_URI，用于获取cusor
    public static final String SMS_URI = "content://sms";//API level>=23,可直接使用Telephony.Sms.CONTENT_URI,用于注册内容观察者
    private static final String[] PROJECTION = new String[]{
            Telephony.Sms._ID,
            Telephony.Sms.ADDRESS,
            Telephony.Sms.BODY,
            Telephony.Sms.DATE
    };
    private Context context;
    private String smsBodyStart;
    private String smsBodyContains;
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public ReadSmsObserver(Context context,String smsBodyStart,String smsBodyContains) {
        super(null);
        this.context=context;
        this.smsBodyStart=smsBodyStart;
        this.smsBodyContains=smsBodyContains;
    }



    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        // 读取短信收件箱，只读取未读短信，即read=0，并按照默认排序
        Cursor cursor = context.getContentResolver().query(Uri.parse(SMS_INBOX_URI), PROJECTION,
                Telephony.Sms.READ + "=?", new String[]{"0"}, Telephony.Sms.Inbox.DEFAULT_SORT_ORDER);
        if (cursor == null) return;

        while (cursor.moveToNext()) {
            // 读取短信发送人
            String address = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            // 读取短息内容
            String smsBody = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            // 检查短信发送者，和短信内容
            if (checkSmsBody(smsBody)) {
                // 解析短信内容，得到验证码
                String smsCode = parseSmsBody(smsBody);
                //发送短信验证码到UI
                EventBus.getDefault().post(new SmsChangeEvent(smsCode));
                // 关闭cursor的方法
                closeCursor(cursor);
                return;
            }
        }
        // 关闭cursor的方法
        closeCursor(cursor);
    }
    /**
     * @param smsBody
     * @return
     */
    private boolean checkSmsBody(String smsBody) {
        if (!TextUtils.isEmpty(getSmsBodyStart()) && !TextUtils.isEmpty(getSmsBodyContains())) {
            return smsBody.startsWith(getSmsBodyStart()) && smsBody.contains(getSmsBodyContains());
        } else if (!TextUtils.isEmpty(getSmsBodyStart())) {
            return smsBody.startsWith(getSmsBodyStart());
        } else if (!TextUtils.isEmpty(getSmsBodyContains())) {
            return smsBody.contains(getSmsBodyContains());
        } else {
            return true;
        }
    }

    private String getSmsBodyStart() {
        return smsBodyStart;
    }
    private String getSmsBodyContains(){
        return  smsBodyContains;
    }

    private void closeCursor(Cursor cursor) {
        cursor.close();
    }

    /**
     * 解析短信得到验证码
     *
     * @param smsBody
     * @return 验证码
     */
    private String parseSmsBody(String smsBody) {
        String regex = new String("(\\d{4})");// 匹配规则为短信中的连续4位数字
        String smsCode = "";// 验证码

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(smsBody);

        while (matcher.find()) {// 如果匹配到了
            smsCode = matcher.group(0);
        }
        Log.w("ReadSmsObserver", "smsCode = " + smsCode);
        return smsCode;
    }
}